import tkinter as tk
from tkinter import messagebox, ttk, scrolledtext
import requests
import threading

class ConsultationWindow:
    def __init__(self, parent, main_app):
        self.main_app = main_app
        self.root = parent
        
        # 清空主窗口
        for widget in self.root.winfo_children():
            widget.destroy()
        
        self.create_widgets()
        self.load_user_points()
        self.load_consultation_history()
    
    def create_widgets(self):
        # 顶部导航栏
        nav_frame = tk.Frame(self.root, bg='#34495e', height=60)
        nav_frame.pack(fill='x', side='top')
        nav_frame.pack_propagate(False)
        
        # 用户信息
        user_info = f"欢迎，{self.main_app.current_user['name']} ({self.main_app.current_user['username']})"
        user_label = tk.Label(
            nav_frame,
            text=user_info,
            font=("Arial", 12, "bold"),
            bg='#34495e',
            fg='white'
        )
        user_label.pack(side='left', padx=20, pady=20)
        
        # 积分显示
        self.points_label = tk.Label(
            nav_frame,
            text="积分: 加载中...",
            font=("Arial", 12),
            bg='#34495e',
            fg='#f39c12'
        )
        self.points_label.pack(side='left', padx=20, pady=20)
        
        # 导航按钮
        nav_buttons_frame = tk.Frame(nav_frame, bg='#34495e')
        nav_buttons_frame.pack(side='right', padx=20, pady=20)
        
        history_btn = tk.Button(
            nav_buttons_frame,
            text="咨询记录",
            command=self.show_history,
            font=("Arial", 10),
            bg='#3498db',
            fg='white'
        )
        history_btn.pack(side='left', padx=5)
        
        logout_btn = tk.Button(
            nav_buttons_frame,
            text="退出登录",
            command=self.main_app.logout,
            font=("Arial", 10),
            bg='#e74c3c',
            fg='white'
        )
        logout_btn.pack(side='left', padx=5)
        
        # 主内容区域
        main_frame = tk.Frame(self.root, bg='#f0f0f0')
        main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 咨询表单
        form_frame = tk.LabelFrame(
            main_frame,
            text="购车咨询",
            font=("Arial", 14, "bold"),
            bg='#f0f0f0',
            fg='#2c3e50',
            padx=20,
            pady=20
        )
        form_frame.pack(fill='x', pady=(0, 20))
        
        # 预算范围
        tk.Label(form_frame, text="购车预算范围*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=0, column=0, sticky='e', pady=10, padx=5)
        self.budget_combobox = ttk.Combobox(
            form_frame,
            values=["5-10万元", "10-15万元", "15-20万元", "20-30万元", "30-50万元", "50万元以上"],
            font=("Arial", 12),
            width=25,
            state="readonly"
        )
        self.budget_combobox.grid(row=0, column=1, pady=10, padx=5, sticky='w')
        self.budget_combobox.set("10-15万元")
        
        # 偏好车型
        tk.Label(form_frame, text="偏好车型*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=1, column=0, sticky='e', pady=10, padx=5)
        self.type_combobox = ttk.Combobox(
            form_frame,
            values=["SUV", "轿车", "MPV", "跑车", "皮卡", "无特定偏好"],
            font=("Arial", 12),
            width=25,
            state="readonly"
        )
        self.type_combobox.grid(row=1, column=1, pady=10, padx=5, sticky='w')
        self.type_combobox.set("SUV")
        
        # 使用场景
        tk.Label(form_frame, text="主要使用场景*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=2, column=0, sticky='e', pady=10, padx=5)
        self.usage_combobox = ttk.Combobox(
            form_frame,
            values=["城市通勤", "家庭使用", "商务接待", "长途旅行", "越野户外", "多种场景"],
            font=("Arial", 12),
            width=25,
            state="readonly"
        )
        self.usage_combobox.grid(row=2, column=1, pady=10, padx=5, sticky='w')
        self.usage_combobox.set("城市通勤")
        
        # 燃料类型
        tk.Label(form_frame, text="燃料类型偏好*:", bg='#f0f0f0', font=("Arial", 12)).grid(row=3, column=0, sticky='e', pady=10, padx=5)
        self.fuel_combobox = ttk.Combobox(
            form_frame,
            values=["燃油", "电动", "混动", "无特定偏好"],
            font=("Arial", 12),
            width=25,
            state="readonly"
        )
        self.fuel_combobox.grid(row=3, column=1, pady=10, padx=5, sticky='w')
        self.fuel_combobox.set("无特定偏好")
        
        # 品牌偏好
        tk.Label(form_frame, text="品牌偏好:", bg='#f0f0f0', font=("Arial", 12)).grid(row=4, column=0, sticky='e', pady=10, padx=5)
        self.brand_entry = tk.Entry(form_frame, font=("Arial", 12), width=27)
        self.brand_entry.grid(row=4, column=1, pady=10, padx=5, sticky='w')
        self.brand_entry.insert(0, "无特定偏好")
        
        # 咨询按钮
        consult_btn = tk.Button(
            form_frame,
            text="开始AI咨询",
            command=self.start_consultation,
            font=("Arial", 12, "bold"),
            bg='#e74c3c',
            fg='white',
            width=15,
            height=2
        )
        consult_btn.grid(row=5, column=0, columnspan=2, pady=20)
        
        # 咨询结果区域
        result_frame = tk.LabelFrame(
            main_frame,
            text="咨询结果",
            font=("Arial", 14, "bold"),
            bg='#f0f0f0',
            fg='#2c3e50',
            padx=20,
            pady=20
        )
        result_frame.pack(fill='both', expand=True)
        
        # 加载提示
        self.loading_label = tk.Label(
            result_frame,
            text="请开始咨询以查看结果...",
            font=("Arial", 12),
            bg='#f0f0f0',
            fg='#7f8c8d'
        )
        self.loading_label.pack(pady=20)
        
        # 结果文本框
        self.result_text = scrolledtext.ScrolledText(
            result_frame,
            font=("Arial", 11),
            wrap=tk.WORD,
            height=15,
            state=tk.DISABLED
        )
        self.result_text.pack(fill='both', expand=True)
        
        # 历史记录区域（初始隐藏）
        self.history_frame = tk.LabelFrame(
            main_frame,
            text="咨询记录",
            font=("Arial", 14, "bold"),
            bg='#f0f0f0',
            fg='#2c3e50',
            padx=20,
            pady=20
        )
    
    def load_user_points(self):
        """加载用户积分"""
        try:
            response = requests.get(
                f"{self.main_app.api_base}/user/points/{self.main_app.current_user['id']}"
            )
            result = response.json()
            if result['success']:
                self.points_label.config(text=f"积分: {result['points']}")
        except:
            self.points_label.config(text="积分: 加载失败")
    
    def start_consultation(self):
        """开始咨询"""
        # 获取表单数据
        budget_range = self.budget_combobox.get()
        preferred_type = self.type_combobox.get()
        usage_scenario = self.usage_combobox.get()
        fuel_type = self.fuel_combobox.get()
        brand_preference = self.brand_entry.get()
        
        if not all([budget_range, preferred_type, usage_scenario, fuel_type]):
            messagebox.showerror("错误", "请填写所有必填字段")
            return
        
        # 显示加载中
        self.loading_label.config(text="AI正在分析您的需求，请稍候...")
        self.result_text.config(state=tk.NORMAL)
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, "正在连接AI服务，请耐心等待...")
        self.result_text.config(state=tk.DISABLED)
        
        # 在新线程中执行咨询
        thread = threading.Thread(
            target=self.perform_consultation,
            args=(budget_range, preferred_type, usage_scenario, fuel_type, brand_preference)
        )
        thread.daemon = True
        thread.start()
    
    def perform_consultation(self, budget_range, preferred_type, usage_scenario, fuel_type, brand_preference):
        """执行咨询请求"""
        try:
            response = requests.post(
                f"{self.main_app.api_base}/consult",
                json={
                    "user_id": self.main_app.current_user['id'],
                    "budget_range": budget_range,
                    "preferred_type": preferred_type,
                    "usage_scenario": usage_scenario,
                    "fuel_type": fuel_type,
                    "brand_preference": brand_preference
                }
            )
            result = response.json()
            
            # 在主线程中更新UI
            self.root.after(0, self.update_consultation_result, result)
            
        except Exception as e:
            error_result = {'success': False, 'message': f'咨询失败: {str(e)}'}
            self.root.after(0, self.update_consultation_result, error_result)
    
    def update_consultation_result(self, result):
        """更新咨询结果"""
        self.loading_label.pack_forget()
        
        self.result_text.config(state=tk.NORMAL)
        self.result_text.delete(1.0, tk.END)
        
        if result['success']:
            # 显示成功结果
            self.result_text.insert(tk.END, result['response'])
            
            # 更新积分
            self.load_user_points()
            
            # 重新加载历史记录
            self.load_consultation_history()
            
            messagebox.showinfo("成功", f"咨询完成！获得{result['points_added']}积分")
        else:
            # 显示错误信息
            self.result_text.insert(tk.END, f"咨询失败:\n{result['message']}")
            messagebox.showerror("错误", result['message'])
        
        self.result_text.config(state=tk.DISABLED)
    
    def show_history(self):
        """显示咨询记录"""
        if self.history_frame.winfo_ismapped():
            self.history_frame.pack_forget()
            return
        
        # 确保结果区域隐藏
        self.result_text.master.pack_forget()
        self.loading_label.pack(pady=20)
        
        # 显示历史记录
        self.history_frame.pack(fill='both', expand=True)
        
        # 清空历史记录区域
        for widget in self.history_frame.winfo_children():
            widget.destroy()
        
        # 创建历史记录列表
        if hasattr(self, 'consultation_history') and self.consultation_history:
            for i, consult in enumerate(self.consultation_history):
                consult_frame = tk.Frame(self.history_frame, bg='#ecf0f1', relief='raised', bd=1)
                consult_frame.pack(fill='x', padx=5, pady=5)
                
                # 咨询基本信息
                info_text = f"{consult['created_at']} - 预算:{consult['budget_range']} - 车型:{consult['preferred_type']} - 场景:{consult['usage_scenario']}"
                info_label = tk.Label(
                    consult_frame,
                    text=info_text,
                    font=("Arial", 10),
                    bg='#ecf0f1',
                    fg='#2c3e50',
                    anchor='w'
                )
                info_label.pack(fill='x', padx=10, pady=5)
                
                # 预览响应
                preview_label = tk.Label(
                    consult_frame,
                    text=consult['llm_response'],
                    font=("Arial", 9),
                    bg='#ecf0f1',
                    fg='#7f8c8d',
                    anchor='w',
                    justify='left'
                )
                preview_label.pack(fill='x', padx=10, pady=(0, 5))
                
                # 查看详情按钮
                detail_btn = tk.Button(
                    consult_frame,
                    text="查看详情",
                    command=lambda cid=consult['id']: self.show_consultation_detail(cid),
                    font=("Arial", 8),
                    bg='#3498db',
                    fg='white'
                )
                detail_btn.pack(side='right', padx=10, pady=5)
        else:
            no_history_label = tk.Label(
                self.history_frame,
                text="暂无咨询记录",
                font=("Arial", 12),
                bg='#f0f0f0',
                fg='#7f8c8d'
            )
            no_history_label.pack(pady=20)
        
        # 返回按钮
        back_btn = tk.Button(
            self.history_frame,
            text="返回咨询",
            command=self.hide_history,
            font=("Arial", 10),
            bg='#95a5a6',
            fg='white'
        )
        back_btn.pack(pady=10)
    
    def hide_history(self):
        """隐藏历史记录"""
        self.history_frame.pack_forget()
        self.result_text.master.pack(fill='both', expand=True)
    
    def load_consultation_history(self):
        """加载咨询历史记录"""
        try:
            response = requests.get(
                f"{self.main_app.api_base}/consultations/{self.main_app.current_user['id']}"
            )
            result = response.json()
            if result['success']:
                self.consultation_history = result['consultations']
        except:
            self.consultation_history = []
    
    def show_consultation_detail(self, consultation_id):
        """显示咨询详情"""
        try:
            response = requests.get(
                f"{self.main_app.api_base}/consultation/{consultation_id}"
            )
            result = response.json()
            
            if result['success']:
                consult = result['consultation']
                
                # 创建详情窗口
                detail_window = tk.Toplevel(self.root)
                detail_window.title("咨询详情")
                detail_window.geometry("700x500")
                
                # 咨询信息
                info_frame = tk.Frame(detail_window, padx=20, pady=10)
                info_frame.pack(fill='x')
                
                info_text = f"咨询时间: {consult['created_at']}\n预算范围: {consult['budget_range']}\n偏好车型: {consult['preferred_type']}\n使用场景: {consult['usage_scenario']}\n燃料类型: {consult['fuel_type']}\n品牌偏好: {consult['brand_preference']}"
                
                info_label = tk.Label(
                    info_frame,
                    text=info_text,
                    font=("Arial", 11),
                    justify='left',
                    anchor='w'
                )
                info_label.pack(fill='x')
                
                # 分隔线
                ttk.Separator(detail_window, orient='horizontal').pack(fill='x', padx=20, pady=10)
                
                # AI响应
                response_label = tk.Label(
                    detail_window,
                    text="AI推荐结果:",
                    font=("Arial", 12, "bold")
                )
                response_label.pack(anchor='w', padx=20, pady=(0, 10))
                
                response_text = scrolledtext.ScrolledText(
                    detail_window,
                    font=("Arial", 11),
                    wrap=tk.WORD
                )
                response_text.pack(fill='both', expand=True, padx=20, pady=(0, 20))
                response_text.insert(tk.END, consult['llm_response'])
                response_text.config(state=tk.DISABLED)
                
            else:
                messagebox.showerror("错误", "无法加载咨询详情")
        except Exception as e:
            messagebox.showerror("错误", f"加载详情失败: {str(e)}")